package com.pureut.order.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.order.domain.CustomerComplaintsManagement;
import com.pureut.order.domain.CustomerComplaintsSolution;
import com.pureut.order.domain.CustomerManagement;
import com.pureut.order.domain.SalesOrder;
import com.pureut.order.dto.*;
import com.pureut.order.mapper.CustomerComplaintsManagementMapper;
import com.pureut.order.mapper.CustomerComplaintsSolutionMapper;
import com.pureut.order.mapper.SalesOrderDetailMapper;
import com.pureut.order.mapper.SalesOrderMapper;
import com.pureut.order.service.CustomerComplaintsManagementService;
import com.pureut.order.service.CustomerManagementService;
import com.pureut.order.vo.ComplaintsVo;
import com.pureut.order.vo.CustomerComplaintsManagementVo;
import com.pureut.order.vo.OrderReviewVo;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.StorageFegin;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.PickingSaleVo;
import com.pureut.system.api.vo.SysAuditHistoryVo;
import com.pureut.system.api.vo.SysWorkbenchAuditAgentVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/***
 *
 * Author:C
 * Date:2022/11/30 10:16
 * @DESC
 */
@Service
public class CustomerComplaintsManagementServiceImpl extends ServiceImpl<CustomerComplaintsManagementMapper, CustomerComplaintsManagement>
        implements CustomerComplaintsManagementService {

    @Resource
    CustomerComplaintsManagementMapper customerComplaintsManagementMapper;

    @Resource
    CustomerManagementService customerManagementService;

    @Resource
    CustomerComplaintsSolutionMapper customerComplaintsSolutionMapper;

    @Resource
    FeignService feignService;

    @Resource
    StorageFegin storageFegin;

    @Resource
    SalesOrderDetailMapper salesOrderDetailMapper;

    @Resource
    SalesOrderMapper salesOrderMapper;

    /**
     * 客诉管理列表
     *
     * @param customerComplaintsManagementVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<CustomerComplaintsManagementDto> getList(CustomerComplaintsManagementVo customerComplaintsManagementVo) {
        //获取客诉信息
        List<CustomerComplaintsManagementDto> customerComplaintsManagementList = customerComplaintsManagementMapper.getCustomerComplaintsManagementList(customerComplaintsManagementVo);
        //获取客诉管理状态缓存字典数据
        List<SysDictData> statusArray = DictUtils.getDictCache("customer_complaints_review_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (CustomerComplaintsManagementDto entity : customerComplaintsManagementList) {

            entity.setCustomerReviewStatusDict(statusMap.get(entity.getCustomerReviewStatus()));
        }
        return customerComplaintsManagementList;
    }

    /**
     * 新增客诉信息
     *
     * @param customerComplaintsManagementVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addCustomerComplaintsManagement(CustomerComplaintsManagementVo customerComplaintsManagementVo) {
        CustomerComplaintsManagement customerComplaintsManagement = new CustomerComplaintsManagement();
        List<ComplaintsVo> complaintsList = customerComplaintsManagementVo.getComplaintsList();
        for (ComplaintsVo entity : complaintsList) {
            customerComplaintsManagement.setCustomerId(customerComplaintsManagementVo.getCustomerId());
            customerComplaintsManagement.setOrderType(Integer.parseInt(customerComplaintsManagementVo.getOrderType()));
            customerComplaintsManagement.setSalesDocumentNum(customerComplaintsManagementVo.getSalesDocumentNum());
            customerComplaintsManagement.setComplaints(customerComplaintsManagementVo.getComplaints());
            customerComplaintsManagement.setEnclosureUrl(customerComplaintsManagementVo.getEnclosureUrl());
            customerComplaintsManagement.setMaterialId(entity.getMaterialId());
            customerComplaintsManagement.setMaterialCode(entity.getMaterialCode());
            customerComplaintsManagement.setCustomerReviewStatus(1);
            customerComplaintsManagement.setCreateBy(SecurityUtils.getUsername());
            customerComplaintsManagement.setCreateTime(new Date());
            customerComplaintsManagement.setDeptId(SecurityUtils.getDeptId());
        }
        return save(customerComplaintsManagement);
    }

    /**
     * 提交审核
     *
     * @param id
     * @return
     */
    @Override
    public boolean submitReview(Long id) {
        CustomerComplaintsManagement customerComplaintsManagement = getById(id);
        if (customerComplaintsManagement.getCustomerReviewStatus() == 1) {
            customerComplaintsManagement.setCustomerReviewStatus(2);


            SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();
            sysWorkbenchAuditAgentVo.setDocConfig("order:sale:complaints:review");
            sysWorkbenchAuditAgentVo.setReceiptName("客诉管理");
            sysWorkbenchAuditAgentVo.setReceiptNumber(customerComplaintsManagement.getSalesDocumentNum());//
            sysWorkbenchAuditAgentVo.setStatus(1);//待审核
            sysWorkbenchAuditAgentVo.setReceiptContent("有单据待审核,请及时审核");

            feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);

            return updateById(customerComplaintsManagement);
        } else {
            throw new GlobalException("只能对待提交的客诉进行提交审核");
        }

    }

    /**
     * 撤销审核
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteReview(Long id) {
        CustomerComplaintsManagement customerComplaintsManagement = getById(id);
        if (2 == customerComplaintsManagement.getCustomerReviewStatus() || 5 == customerComplaintsManagement.getCustomerReviewStatus()) {
            customerComplaintsManagement.setCustomerReviewStatus(1);

            feignService.deleteDoc(customerComplaintsManagement.getSalesDocumentNum(),"客诉管理");

            return updateById(customerComplaintsManagement);
        } else {
            throw new GlobalException("只能对待审核的客诉和方案进行撤销审核");
        }
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public boolean deleteCustomerComplaintsManagement(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<CustomerComplaintsManagement> customerComplaintsManagementList = new ArrayList<>();
        if (idList.size() > 0) {
            //获取客诉信息
            List<CustomerComplaintsManagement> customerComplaintsManagements = customerComplaintsManagementMapper.selectList(new QueryWrapper<CustomerComplaintsManagement>().lambda().in(CustomerComplaintsManagement::getId, ids));
            for (CustomerComplaintsManagement entity : customerComplaintsManagements) {
                //判断是否有提交的
                if (1 == entity.getCustomerReviewStatus()) {
                    customerComplaintsManagementList.add(entity);
                    feignService.deleteDoc(entity.getSalesDocumentNum(),"客诉管理");
                }
            }
        }
        if (customerComplaintsManagementList.size() != 0) {



            return removeByIds(customerComplaintsManagementList);
        } else {
            throw new GlobalException("没有满足条件的数据");
        }
    }

    /**
     * 查看
     *
     * @param id
     * @return
     */
    @Override
    public CustomerComplaintsSolutionDto viewSolution(Long id) {

        CustomerComplaintsSolutionDto viewSolution = customerComplaintsManagementMapper.getViewSolution(id);
        //获取客户信息
        CustomerManagement customerManagement = customerManagementService.getById(viewSolution.getCustomerId());
        viewSolution.setCustomerName(customerManagement.getCustomerName());
        viewSolution.setCustomerNum(customerManagement.getCustomerNum());
        //获取客诉管理状态缓存字典数据
        List<SysDictData> statusArray = DictUtils.getDictCache("customer_complaints_order_type");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //获取采购计划质量标准
        List<SysDictData> standardArray = DictUtils.getDictCache("quality_standard");
        Map<String, String> standardMap = standardArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        viewSolution.setOrderType(viewSolution.getOrderType());
        viewSolution.setOrderTypeDict(statusMap.get(viewSolution.getOrderType()));

        if (viewSolution.getSolution() != null) {
            //获取客诉解决方案缓存字典数据
            List<SysDictData> arrayList = DictUtils.getDictCache("solution_type");
            Map<String, String> arrayMap = arrayList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            viewSolution.setSolution(viewSolution.getSolution());
            viewSolution.setSolutionDict(arrayMap.get(viewSolution.getSolution()));
        }
        //获取网型标准缓存字典数据
        List<SysDictData> netArray = DictUtils.getDictCache("sys_of_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取铺网类型标准缓存字典数据
        List<SysDictData> netTypeArray = DictUtils.getDictCache("sys_type_net");
        Map<String, String> netTypeMap = netTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<MaterialDto> materialDtoList = new ArrayList<>();
        MaterialDto materialDto = new MaterialDto();
        PickingSaleVo pickingSaleVo = new PickingSaleVo();
        pickingSaleVo.setWodDocNum(viewSolution.getSalesDocumentNum());
        AjaxResult byCustomerComplaintsList = storageFegin.getByCustomerComplaintsList(pickingSaleVo);
        //获取销售发货列表
        List<PickingSaleDto> data = JSON.parseArray(JSON.toJSONString(byCustomerComplaintsList.get("data")), PickingSaleDto.class);
        PickingSaleDto pickingSaleDto = new PickingSaleDto();

        for (PickingSaleDto entity : data) {
            if (entity.getWodDocNum().equals(viewSolution.getSalesDocumentNum())) {
                BeanUtils.copyProperties(entity, pickingSaleDto);
                break;
            }
        }
        //获取销售订单
        SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, pickingSaleDto.getConnectionId()));

        //获取销售明细列表
        List<SalesOrderDetailDto> detailList = salesOrderDetailMapper.getDetailList(salesOrder.getId());

        for (SalesOrderDetailDto entity : detailList) {
            if (entity.getMaterialCode().equals(viewSolution.getMaterialCode())) {
                materialDto.setMaterialCode(entity.getMaterialCode());
                materialDto.setMaterialName(entity.getMaterialName());
                materialDto.setMaterialSpec(entity.getMaterialSpec());
                materialDto.setMaterialNet(entity.getMaterialNet());
                materialDto.setMaterialNetType(entity.getMaterialNetType());
                materialDto.setMaterialRatio(entity.getMaterialRatio());
                materialDto.setMaterialGheavy(viewSolution.getMaterialGheavy());
                materialDto.setWidthCloth(entity.getWidthCloth());
                materialDto.setRollDiameter(entity.getRollDiameter());
                materialDto.setQualityStandard(entity.getQualityStandard());
            }
        }
        materialDto.setMaterialNetTypeDict(netTypeMap.get(materialDto.getMaterialNetType()));
        materialDto.setMaterialNetDict(netMap.get(materialDto.getMaterialNet()));
        materialDto.setQualityStandardDict(standardMap.get(materialDto.getQualityStandard()));

        materialDto.setBatchNum(viewSolution.getBatchNum());
        materialDtoList.add(materialDto);
        viewSolution.setMaterialList(materialDtoList);
        return viewSolution;
    }


    /**
     * 修改
     *
     * @param customerComplaintsManagementVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCustomerComplaintsById(CustomerComplaintsManagementVo customerComplaintsManagementVo) {
        //获取订单数据
        CustomerComplaintsManagement customerComplaintsManagement = getById(customerComplaintsManagementVo.getId());
        boolean isTrue = 1 == customerComplaintsManagement.getCustomerReviewStatus() || 9 == customerComplaintsManagement.getCustomerReviewStatus();
        SysAuditHistoryVo sysAuditHistoryVo = new SysAuditHistoryVo();
        //如果是待提交或者客诉未通过就修改客诉数据,否则就修改解决方案数据
        if (isTrue) {
            List<ComplaintsVo> complaintsList = customerComplaintsManagementVo.getComplaintsList();
            for (ComplaintsVo entity : complaintsList) {
                customerComplaintsManagement.setCustomerId(customerComplaintsManagementVo.getCustomerId());
//                customerComplaintsManagement.setOrderType(Integer.parseInt(customerComplaintsManagementVo.getOrderType()));
                customerComplaintsManagement.setSalesDocumentNum(customerComplaintsManagementVo.getSalesDocumentNum());
                customerComplaintsManagement.setComplaints(customerComplaintsManagementVo.getComplaints());
                customerComplaintsManagement.setEnclosureUrl(customerComplaintsManagementVo.getEnclosureUrl());
                customerComplaintsManagement.setMaterialId(entity.getMaterialId());
                customerComplaintsManagement.setMaterialCode(entity.getMaterialCode());

            }
            if (customerComplaintsManagement.getCustomerReviewStatus() == 9) {
                //调用审核
                String perms = "order:sale:complaints:review";
                String auditDoc = customerComplaintsManagement.getSalesDocumentNum();
                sysAuditHistoryVo.setAuditDoc(auditDoc);
                sysAuditHistoryVo.setPerms(perms);
                AjaxResult history = feignService.editHistory(sysAuditHistoryVo);
                String data = JSON.parseObject(JSON.toJSONString(history.get("msg")), String.class);
                if ("操作成功".equals(data)) {
                    customerComplaintsManagement.setCustomerReviewStatus(2);

                    //修改审核代办状态为已处理
                    feignService.updateStatus(3,customerComplaintsManagement.getSalesDocumentNum(),"客诉管理");//

                    return updateById(customerComplaintsManagement);
                } else {
                    return false;
                }
            }
            customerComplaintsManagement.setCustomerReviewStatus(2);
            return updateById(customerComplaintsManagement);
        } else if (6 == customerComplaintsManagement.getCustomerReviewStatus()) {
            CustomerComplaintsSolution customerComplaintsSolution = customerComplaintsSolutionMapper.selectOne(new QueryWrapper<CustomerComplaintsSolution>().lambda().eq(CustomerComplaintsSolution::getCustomerComplaintsId, customerComplaintsManagementVo.getId()));
            BeanUtils.copyProperties(customerComplaintsManagementVo, customerComplaintsSolution);
            customerComplaintsSolution.setSolution(Integer.parseInt(customerComplaintsManagementVo.getSolution()));
            customerComplaintsSolution.setSolutionRemark(customerComplaintsManagementVo.getSolutionRemark());
            customerComplaintsSolution.setSolutionUrl(customerComplaintsManagementVo.getSolutionUrl());
            customerComplaintsSolutionMapper.updateById(customerComplaintsSolution);
            customerComplaintsManagement.setCustomerReviewStatus(5);
            updateById(customerComplaintsManagement);
            //调用审核
            String perms = "order:sale:complaints:programmeReview";
            String auditDoc = customerComplaintsManagement.getSalesDocumentNum() + customerComplaintsManagement.getId();
            sysAuditHistoryVo.setAuditDoc(auditDoc);
            sysAuditHistoryVo.setPerms(perms);
            AjaxResult history = feignService.editHistory(sysAuditHistoryVo);
            String data = JSON.parseObject(JSON.toJSONString(history.get("msg")), String.class);

            //修改审核代办状态为已处理
            feignService.updateStatus(3,customerComplaintsManagement.getSalesDocumentNum(),"客诉管理");//

            if ("操作成功".equals(data)) {
                return true;
            } else {
                return false;
            }
        } else {
            throw new GlobalException("只能修改待提交、客诉未通过、方案未通过的客诉信息");
        }
    }

    /**
     * 客诉审核
     *
     * @param orderReviewVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean complaintsReview(OrderReviewVo orderReviewVo) {
        CustomerComplaintsManagement customerComplaintsManagement = getById(orderReviewVo.getId());
        if (customerComplaintsManagement.getCustomerReviewStatus() == 2 || customerComplaintsManagement.getCustomerReviewStatus() == 3) {
            String perms = "order:sale:complaints:review";
            int isAdopt = orderReviewVo.getIsAdopt();
            String auditDoc = customerComplaintsManagement.getSalesDocumentNum();
            String auditRemarks = orderReviewVo.getReviewComments();
            Long userId = SecurityUtils.getUserId();
            AjaxResult sequence = feignService.getSequenceTwo(perms, 2, isAdopt, auditRemarks, auditDoc, userId);
            Integer data = JSON.parseObject(JSON.toJSONString(sequence.get("data")), Integer.class);
            if (data == null) {
                throw new GlobalException("未对该审核进行配置");
            }
            //1:通过，2：审核中，3：没权限 4:该人已经审核过
            if (orderReviewVo.getIsAdopt() == 1) {
                if (data == 1) {
                    customerComplaintsManagement.setCustomerReviewStatus(4);
                    if (customerComplaintsManagement.getCustomerReviewBy() == null) {
                        customerComplaintsManagement.setCustomerReviewBy(SecurityUtils.getUsername());
                    } else {
                        customerComplaintsManagement.setCustomerReviewBy(customerComplaintsManagement.getCustomerReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    customerComplaintsManagement.setCustomerReviewTime(new Date());

                    feignService.updateStatus(3,customerComplaintsManagement.getSalesDocumentNum(),"客诉管理");

                    return updateById(customerComplaintsManagement);
                } else if (data == 2) {
                    customerComplaintsManagement.setCustomerReviewStatus(3);
                    if (customerComplaintsManagement.getCustomerReviewBy() == null) {
                        customerComplaintsManagement.setCustomerReviewBy(SecurityUtils.getUsername());
                    } else {
                        customerComplaintsManagement.setCustomerReviewBy(customerComplaintsManagement.getCustomerReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    customerComplaintsManagement.setCustomerReviewTime(new Date());
                    return updateById(customerComplaintsManagement);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            } else {
                if (data == 1 || data == 2) {
                    customerComplaintsManagement.setCustomerReviewStatus(9);
                    if (customerComplaintsManagement.getCustomerReviewBy() == null) {
                        customerComplaintsManagement.setCustomerReviewBy(SecurityUtils.getUsername());
                    } else {
                        customerComplaintsManagement.setCustomerReviewBy(customerComplaintsManagement.getCustomerReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    customerComplaintsManagement.setCustomerReviewTime(new Date());

                    SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();
                    sysWorkbenchAuditAgentVo.setDocConfig("order:sale:complaints:review");
                    sysWorkbenchAuditAgentVo.setReceiptName("客诉管理");
                    sysWorkbenchAuditAgentVo.setReceiptNumber(customerComplaintsManagement.getSalesDocumentNum());//
                    sysWorkbenchAuditAgentVo.setStatus(2);//待处理

                    sysWorkbenchAuditAgentVo.setPassFlag("1");
                    sysWorkbenchAuditAgentVo.setCreateName(customerComplaintsManagement.getCreateBy());

                    sysWorkbenchAuditAgentVo.setReceiptContent("有单据未通过,请及时查看");

                    feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);

                    return updateById(customerComplaintsManagement);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            }
        } else {
            throw new GlobalException("状态为待审核和审核中的单据才能进行审核");
        }
    }

    /**
     * 方案审核
     *
     * @param orderReviewVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean programmeReview(OrderReviewVo orderReviewVo) {
        CustomerComplaintsManagement customerComplaintsManagement = getById(orderReviewVo.getId());
        if (customerComplaintsManagement.getCustomerReviewStatus() == 5 || customerComplaintsManagement.getCustomerReviewStatus() == 7) {
            String perms = "order:sale:complaints:programmeReview";
            int isAdopt = orderReviewVo.getIsAdopt();
            String auditDoc = customerComplaintsManagement.getSalesDocumentNum() + customerComplaintsManagement.getId();
            String auditRemarks = orderReviewVo.getReviewComments();
            Long userId = SecurityUtils.getUserId();
            AjaxResult sequence = feignService.getSequenceTwo(perms, 2, isAdopt, auditRemarks, auditDoc, userId);
            Integer data = JSON.parseObject(JSON.toJSONString(sequence.get("data")), Integer.class);
            if (data == null) {
                throw new GlobalException("未对该审核进行配置");
            }
            //1:通过，2：审核中，3：没权限 4:该人已经审核过
            if (orderReviewVo.getIsAdopt() == 1) {
                if (data == 1) {
                    customerComplaintsManagement.setCustomerReviewStatus(8);
                    if (customerComplaintsManagement.getProgrammeReviewBy() == null) {
                        customerComplaintsManagement.setProgrammeReviewBy(SecurityUtils.getUsername());
                    } else {
                        customerComplaintsManagement.setProgrammeReviewBy(customerComplaintsManagement.getCustomerReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    customerComplaintsManagement.setProgrammeReviewTime(new Date());
                    return updateById(customerComplaintsManagement);
                } else if (data == 2) {
                    customerComplaintsManagement.setCustomerReviewStatus(7);
                    if (customerComplaintsManagement.getProgrammeReviewBy() == null) {
                        customerComplaintsManagement.setProgrammeReviewBy(SecurityUtils.getUsername());
                    } else {
                        customerComplaintsManagement.setProgrammeReviewBy(customerComplaintsManagement.getCustomerReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    customerComplaintsManagement.setProgrammeReviewTime(new Date());
                    return updateById(customerComplaintsManagement);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            } else {
                if (data == 1 || data == 2) {
                    customerComplaintsManagement.setCustomerReviewStatus(6);
                    if (customerComplaintsManagement.getProgrammeReviewBy() == null) {
                        customerComplaintsManagement.setProgrammeReviewBy(SecurityUtils.getUsername());
                    } else {
                        customerComplaintsManagement.setProgrammeReviewBy(customerComplaintsManagement.getCustomerReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    customerComplaintsManagement.setProgrammeReviewTime(new Date());
                    return updateById(customerComplaintsManagement);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            }
        } else {
            throw new GlobalException("状态为待方案审核和方案审核中的单据才能进行审核");
        }
    }

}
